package com.sanq.product.books.controller;

import com.sanq.product.books.config.Common;
import com.sanq.product.books.config.Redis;
import com.sanq.product.books.entity.vo.SignVo;
import com.sanq.product.books.entity.vo.UsersVo;
import com.sanq.product.books.service.SignService;
import com.sanq.product.books.service.UsersService;
import com.sanq.product.books.utils.SettingUtil;
import com.sanq.product.books.utils.WebUtil;
import com.sanq.product.config.utils.annotation.LogAnnotation;
import com.sanq.product.config.utils.date.LocalDateUtils;
import com.sanq.product.config.utils.entity.Response;
import com.sanq.product.config.utils.web.JsonUtil;
import com.sanq.product.redis.service.JedisPoolService;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

@RestController
@RequestMapping("/app/sign")
public class SignController {

    @Resource
    private SignService signService;
    @Resource
    private JedisPoolService jedisPoolService;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    @Resource
    private UsersService usersService;

    @LogAnnotation(description = "获取连续签到天数")
    @GetMapping(value = "/getSignByUserAndTime")
    public Response getSignByUserAndTime(HttpServletRequest request) {
        String token = Redis.ReplaceKey.getTokenUser(WebUtil.getToken(request));
        UsersVo usersVo = JsonUtil.json2Obj(jedisPoolService.get(token), UsersVo.class);

        SignVo signVo = new SignVo();
        signVo.setUserId(usersVo.getId());
        signVo.setLastSignTime(Common.DateConvert.getYearAndMonth(LocalDateUtils.nowTime()));

        int signCount = signService.getSignByUserAndTime(signVo);

        //如果连续签到天数为10天的话 就将奖励双倍发放 只发放一次
        if (signCount == 10) {
            taskExecutor.execute(() -> {
                int signReward = SettingUtil.getReward() * 2;

                usersVo.setGold(new BigDecimal(signReward).add(usersVo.getGold()));
                int update = usersService.update(usersVo, usersVo.getId());

                if (update != 0)
                    jedisPoolService.set(token, JsonUtil.obj2Json(usersVo));
            });
        }

        return new Response().success(signCount);
    }
}